using System;
using JNPF.Basics.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JNPF.Utils;
using System.Transactions;
using NPOI.POIFS.FileSystem;
using System.Web;
using NPOI.Util;
using JNPF.Utils.Extensions;

namespace JNPF.Basics.Logic
{
    public class CustomerbaseBll
    {
        private CustomerbaseIService service = new CustomerbaseService();


        private UserIService userService = new UserService();

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<CustomerbaseEntity> GetInfo(int id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="customerName">企业名称</param>
        /// <returns></returns>
        public async Task<CustomerbaseEntity> GetInfo(string customerName)
        {
            try
            {
                return await service.GetInfo(customerName);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        ///根据用户名称 获取信息
        /// </summary>
        /// <param name="socialCreditCode">统一信用代码</param>
        /// <returns></returns>
        public async Task<CustomerbaseEntity> GetInfoBySocialCreditCode(string socialCreditCode)
        {
            try
            {
                return await service.GetInfoBySocialCreditCode(socialCreditCode);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerbaseEntity>> GetPageList(CustomerbaseListQueryInput input)
        {
            try
            {
                return await service.GetPageList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerbaseListOutput>> GetPageListByuserId(CustomerbaseListQueryInput input)
        {
            try
            {
                return await service.GetPageList(input, input.userId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


        /// <summary>
        /// 企业用户  ===  手机号码对应起来的 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<CustomerbaseListOutput>> GetBusPageList(CustomerbaseListQueryInput input)
        {
            try
            {
                return await service.GetBusPageList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 客户经理列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerbaseListOutput>> GetCuseBusList(CustomerbaseListQueryInput input)
        {
            try
            {
                return await service.GetCuseBusList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }



        /// <summary>
        /// 信贷管家   列表（分页）
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        public async Task<PageResult<CustomerbaseListOutput>> GetPagCuseList(CustomerbaseListQueryInput input)
        {
            try
            {
                return await service.GetPagCuseList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }






        /// <summary>
        /// 创建信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Create(CustomerbaseEntity entity)
        {
            try
            {

                entity.CreatorTime = DateTime.Now;
                entity.PartnerUserId = UserProvider.Instance.Get().UserId;
                entity.PartnerUserRealName = UserProvider.Instance.Get().UserName;
                entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                entity.CreatorUser = UserProvider.Instance.Get().UserName;
                entity.DeleteMark = 0;
                return await service.Create(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Update(int id, CustomerbaseEntity entity)
        {
            try
            {
                entity.Id = id;
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyUserId = UserProvider.Instance.Get().UserId;

                return await service.Update(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }



        /// <summary>
        /// 录入首页推送信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> newneedsEntityInsert(NewneedsEntity newneedsEntity)
        {
            try
            {
                return await service.newneedsEntityInsert(newneedsEntity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }


        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task Reviewer(CustomerbaseEntity cusEntity)
        {
            try
            {
                //更新客户表状态
                cusEntity.CurrentState = 1;

                //判断当前用户是否已经创建
                UserEntity userEntity = await userService.GetInfoByAccount(cusEntity.MobilePhone);
                //id为null
                if (userEntity == null || string.IsNullOrEmpty(userEntity.Id))
                {
                    #region 用户表单
                    UserEntity entity = new UserEntity();
                    entity.RealName = cusEntity.LinkName;
                    entity.Account = cusEntity.MobilePhone;
                    entity.MobilePhone = cusEntity.MobilePhone;
                    entity.Id = CommonHelper.Guid;
                    entity.QuickQuery = PinyinHelper.PinyinString(entity.RealName);
                    entity.Secretkey = CommonHelper.Guid.ToString();
                    entity.Password = string.IsNullOrEmpty(entity.Password) ? Md5Helper.md5("e10adc3949ba59abbe56e057f20f883e" + entity.Secretkey).ToLower() : Md5Helper.md5(entity.Password.ToLower() + entity.Secretkey).ToLower();

                    entity.OrganizeId = "a214033e07604487863210490277f8ce"; //企业客户 部门
                    entity.CreatorTime = DateTime.Now;
                    entity.LastModifyTime = DateTime.Now;
                    entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                    entity.EnabledMark = 1;
                    entity.RoleId = "7037cc3a4a8f4e0f9784b884cd324d54"; //企业用户
                    #endregion

                    #region 用户关系
                    List<UserRelationEntity> userRelationList = new List<UserRelationEntity>();

                    //关联角色
                    if (entity.RoleId != null)
                    {
                        var roleId = new List<string>(entity.RoleId.Split(','));
                        foreach (var item in roleId)
                        {
                            UserRelationEntity relationEntity = new UserRelationEntity();
                            relationEntity.Id = CommonHelper.Guid;
                            relationEntity.ObjectType = "Role";
                            relationEntity.ObjectId = item;
                            relationEntity.SortCode = roleId.IndexOf(item);
                            relationEntity.UserId = entity.Id;
                            relationEntity.CreatorTime = entity.CreatorTime;
                            relationEntity.CreatorUserId = entity.CreatorUserId;
                            userRelationList.Add(relationEntity);
                        }
                    }
                    #endregion

                    await service.Create(cusEntity, entity, userRelationList);

                }
                else
                {
                    //看看是否包含企业用户角色
                    if (!userEntity.RoleId.Contains("7037cc3a4a8f4e0f9784b884cd324d54"))
                    {
                        //没有的话给他加一个
                        userEntity.RoleId += ",7037cc3a4a8f4e0f9784b884cd324d54";

                        List<UserRelationEntity> userRelationList = new List<UserRelationEntity>();

                        UserRelationEntity relationEntity = new UserRelationEntity();
                        relationEntity.Id = CommonHelper.Guid;
                        relationEntity.ObjectType = "Role";
                        relationEntity.ObjectId = "7037cc3a4a8f4e0f9784b884cd324d54";
                        relationEntity.SortCode = 0;
                        relationEntity.UserId = userEntity.Id;
                        relationEntity.CreatorTime = userEntity.CreatorTime;
                        relationEntity.CreatorUserId = userEntity.CreatorUserId;

                        userRelationList.Add(relationEntity);

                        await service.Create(cusEntity, userEntity, userRelationList);
                    }
                }

                #region 添加合伙人消息推送信息

                //if (!string.IsNullOrEmpty(cusEntity.HideName))
                //{
                //    string nameStr = "";
                //    for (int i = 0; i < cusEntity.HideName.Length; i++)
                //    {
                //        nameStr += ",*";
                //    }
                //    cusEntity.CustomerName = cusEntity.CustomerName.Replace(cusEntity.HideName, nameStr.Trim(','));
                //}

                //string str = $"欢迎{cusEntity.CustomerName}入驻九士";

                //NewneedsEntity newneedsEntity = new NewneedsEntity();
                //newneedsEntity.Id = Guid.NewGuid().ToString();
                //newneedsEntity.Title = str;
                //newneedsEntity.Description = str;
                //newneedsEntity.UploadDate = DateTime.Now;
                //newneedsEntity.EnabledMark = 1;
                //newneedsEntity.UploadUser = "系统";


                //await service.NewneedsCreate(newneedsEntity);
                #endregion 


            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }

        }




        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns></returns>
        public async Task<int> Delete(CustomerbaseEntity entity)
        {
            try
            {
                entity.DeleteMark = 1;
                entity.DeleteTime = DateTime.Now; ;
                entity.DeleteUserId = UserProvider.Instance.Get().UserId;

                return await service.Update(entity);

                //return await service.Delete(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">过滤条件</param>
        /// <returns></returns>
        public async Task<List<CustomerbaseEntity>> GetList(CustomerbaseListQueryInput input)
        {
            try
            {
                return await service.GetList(input);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }


    }
}